package com.sr.examination.home;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;

import com.sr.examination.R;
import com.sr.examination.category.collection.CollectionActivity;
import com.sr.examination.category.history.HistoryActivity;
import com.sr.examination.category.wrong.WrongActivity;
import com.sr.examination.exam.ExamListActivity;
import com.sr.examination.user.Account;
import com.tl.commonlibrary.event.LoginStatusEvent;
import com.sr.examination.home.adapter.ExamCategoryAdapter;
import com.sr.examination.main.MainActivity;
import com.sr.examination.net.Net;
import com.sr.examination.news.NewsListFragment;
import com.tl.commonlibrary.event.EventUtil;
import com.tl.commonlibrary.network.ErrorResponse;
import com.tl.commonlibrary.network.RequestListener;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.tool.AnimUtil;
import com.tl.commonlibrary.tool.Logger;
import com.tl.commonlibrary.ui.BaseFragment;
import com.tl.commonlibrary.ui.beans.ExamCategory;
import com.tl.commonlibrary.ui.beans.HomeBean;
import com.tl.commonlibrary.ui.widget.NoDataView;
import com.tl.commonlibrary.ui.widget.pull.PullToRefreshLayout;
import com.tl.commonlibrary.ui.widget.pull.PullableScrollView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import retrofit2.Call;

/**
 * @author JongSung
 * @date 2017/6/6 0006
 */
public class HomeFragment extends BaseFragment implements OnRequestListener, PullToRefreshLayout.OnRefreshListener, NewsListFragment.OnLoadNewsListener {

    private NewsListFragment newsListFragment;
    private TextView examCountDownTView, examSummaryTView;
    private GridView categoryGView;
    private PullToRefreshLayout controller;
    private PullableScrollView scrollView;
    private ViewGroup viewGroup;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.frag_home, container, false);
        scrollView = root.findViewById(R.id.scrollView);
        controller = root.findViewById(R.id.scrollViewController);
        controller.enablePullDown(false);
        controller.enablePullUp(false);
        viewGroup = (ViewGroup) inflater.inflate(R.layout.home_container_layout, null);
        scrollView.addView(viewGroup);
        viewGroup.findViewById(R.id.containerLayout).setVisibility(View.GONE);
        viewGroup.findViewById(R.id.wrongExerciseTView).setOnClickListener(this);
        viewGroup.findViewById(R.id.collectionExerciseTView).setOnClickListener(this);
        viewGroup.findViewById(R.id.historyExerciseTView).setOnClickListener(this);
        examCountDownTView = viewGroup.findViewById(R.id.examCountDownTView);
        examSummaryTView = viewGroup.findViewById(R.id.examSummaryTView);
        categoryGView = viewGroup.findViewById(R.id.categoryGView);
        viewGroup.findViewById(R.id.examCategoryLayout).setVisibility(View.GONE);
        categoryGView.setVisibility(View.GONE);
        categoryGView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ExamListActivity.start(context, ((ExamCategoryAdapter) categoryGView.getAdapter()).getItem(position));
            }
        });
        viewGroup.findViewById(R.id.examTimeLayout).setVisibility(View.GONE);
        initNewsList();
        EventUtil.register(this);
        controller.setOnRefreshListener(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void lazyLoad() {
        initData();
        super.lazyLoad();
    }

    private void initData() {
        setTitle(R.string.home);
        if (getTitleBar() != null) {
            TextView menuMineTView = getTitleBar().getLeftView();
            menuMineTView.setText(R.string.menu_mine);
            menuMineTView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            menuMineTView.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
            menuMineTView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onFragmentTriggerd(MainActivity.TAG_TRIGGER_MENU, null);
                }
            });
        }
        refresh();
    }

    private void request() {
        showLoading();
        Net.getHome(com.tl.commonlibrary.ui.user.Account.getLevelId(), new RequestListener<BaseBean<HomeBean>>() {
            @Override
            public void onSuccess(Call<BaseBean<HomeBean>> call, BaseBean<HomeBean> response) {
                if (getContext() == null) {
                    return;
                }
                dismissAll();
                com.tl.commonlibrary.ui.user.Account.LEVEL_ID = response.data.getLevelId();
                ArrayList<ExamCategory> examCategories = response.data.getEntrances();
                if (examCategories != null && !examCategories.isEmpty()) {
//                    examCategories.addAll(examCategories);
//                    examCategories.addAll(examCategories);
                    viewGroup.findViewById(R.id.examCategoryLayout).setVisibility(View.VISIBLE);
                    int len = examCategories.size();
                    categoryGView.setNumColumns(len > 2 ? 3 : (len > 1 ? 2 : 1));
                    categoryGView.setVisibility(View.VISIBLE);
                    categoryGView.setAdapter(new ExamCategoryAdapter(context, examCategories));
                }
                if (newsListFragment != null) {
                    newsListFragment.setDatas(response.data.getNews());
                    controller.enablePullUp(true);
                }
                if (response.data.getExamTime() != null) {
                    examCountDownTView.setText(response.data.getExamTime().getCountDown());
                    examSummaryTView.setText(response.data.getExamTime().getSummary());
                    viewGroup.findViewById(R.id.examTimeLayout).setVisibility(View.VISIBLE);
                }
                View containerLayout = viewGroup.findViewById(R.id.containerLayout);
                containerLayout.setVisibility(View.VISIBLE);
                AnimUtil.startAlphaAnimation(containerLayout, 0f, 1f, 800);
            }

            @Override
            public void onFailed(Call<BaseBean<HomeBean>> call, ErrorResponse errorResponse) {
                Logger.e(tag, errorResponse.toString());
                dismissAll();
                showNoDataView();
            }
        });
    }

    private void initNewsList() {
        newsListFragment = NewsListFragment.get();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        newsListFragment.setListener(this);
        transaction.replace(R.id.newsContainerLayout, newsListFragment);
        transaction.commitAllowingStateLoss();
    }

    public void refresh() {
        viewGroup.postDelayed(new Runnable() {
            @Override
            public void run() {
                request();
            }
        }, 200);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void event(LoginStatusEvent event) {
        request();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //错题
            case R.id.wrongExerciseTView:
                if (Account.isLogged(context)) {
                    WrongActivity.start(context);
                }
                break;
            //收藏
            case R.id.collectionExerciseTView:
                if (Account.isLogged(context)) {
                    CollectionActivity.start(context);
                }
                break;
            //记录
            case R.id.historyExerciseTView:
                if (Account.isLogged(context)) {
                    HistoryActivity.start(context);
                }
                break;

        }
    }

    @Override
    public void onNoDataClicked() {
        super.onNoDataClicked();
        request();
    }

    @Override
    public void onFinished(int from, boolean result) {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventUtil.unRegister(this);
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout, boolean isAuto) {
        controller.finish(PullToRefreshLayout.FAIL);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout, boolean isAuto) {
        if (newsListFragment != null) {
            newsListFragment.loadMore();
        }
    }

    @Override
    public void onMore(int finish) {
        controller.finish(finish);
    }

    @Override
    public void onRefersh(int finish) {
        controller.finish(finish);
    }
}
